package yi.wuhenbot.Utils;

import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.Data;
import java.io.Serializable;
import java.time.Instant;

/**
 * 全局统一响应对象
 * @author wuhen
 * @param <T> 业务数据类型
 */
@Data
@JsonInclude(JsonInclude.Include.NON_NULL)
public class HttpReturn<T> implements Serializable {

    /** 业务状态码 **/
    private int code;

    /** 提示信息 **/
    private String msg;

    /** 业务数据 **/
    private T data;

    /** 时间戳 **/
    private long timestamp = Instant.now().toEpochMilli();

    /** 请求路径（可选） **/
    private String path;

    /** 分页总记录数（可选） **/
    private Long total;

    /*=========== 私有构造 ===========*/
    private HttpReturn() {}

    private HttpReturn(int code, String msg, T data) {
        this.code = code;
        this.msg = msg;
        this.data = data;
    }

    /*=========== 静态工厂 ===========*/

    /** 成功，默认状态码 200 **/
    public static <T> HttpReturn<T> ok() {
        return new HttpReturn<>(200, "success", null);
    }

    public static <T> HttpReturn<T> ok(T data) {
        return new HttpReturn<>(200, "success", data);
    }

    /** 成功，带分页 **/
    public static <T> HttpReturn<T> ok(T data, long total) {
        HttpReturn<T> http = new HttpReturn<>(200, "success", data);
        http.setTotal(total);
        return http;
    }

    /** 失败，自定义状态码 + 提示 **/
    public static <T> HttpReturn<T> fail(int code, String msg) {
        return new HttpReturn<>(code, msg, null);
    }

    /** 失败，默认 500 **/
    public static <T> HttpReturn<T> fail(String msg) {
        return new HttpReturn<>(500, msg, null);
    }

    /** 快捷设置 path，链式 **/
    public HttpReturn<T> path(String path) {
        this.path = path;
        return this;
    }
}